import { navigateTo, showToast, switchTab } from "../../utils/asyncWx";
import { search } from "../../utils/cloud";
import { dateFormate } from "../../utils/util";
// pages/list/list.js
//计时器，十小时更新一次
var timer = 36000000;
var app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        lists: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var userInfo = wx.getStorageSync("userInfo")||[];
        if (userInfo.nickName == null) {
            navigateTo({ url: "../auth/auth" });
            this.freshData(userInfo);
            initData(this);
            return;
        }
        var times = wx.getStorageSync('times');
        var diary = wx.getStorageSync("diary");
        if (Date.now()-times >= timer || diary.length==0) {
            this.freshData(userInfo);
        }
        initData(this);
    },

    /**
    * 生命周期回调——监听小程序启动或切前台。
    */
    onShow: function () {
        initData(this);
        app.data.type = "common";
    },

    /**
     * 监听用户下拉刷新事件,刷新不能低于五分钟
     */
    onPullDownRefresh: function () {
        wx.startPullDownRefresh();
        var time = wx.getStorageSync("time");
        if (Date.now() - time <= 300000) {
            showToast({ title: "刷新频率太频繁" });
            wx.stopPullDownRefresh();
            return;
        }
        var userInfo = wx.getStorageSync("userInfo") || [];
        if (userInfo.nickName==null) {
            navigateTo({ url: "../auth/auth" });
        }
        wx.setStorageSync("time", Date.now());
        this.freshData(userInfo);
        initData(this);
        wx.stopPullDownRefresh();
    },

    /**
     * 读取云数据库刷新数据
     * @param {Object} userInfo 
     */
    async freshData (userInfo) {
        const { data } = await search({
            table: "diary",
            openid: userInfo.openid,
        });
        var diary = [];
        var i = 0;
        if (data.length) {
            data.forEach((item) => {
                diary[i] = item;
                i++;
            })
        }
        wx.setStorageSync("diary", diary);
        // initData(this);
    },

    /**
     * 编辑事件
     */
    edit (e) {
        var { id } = e.currentTarget.dataset;
        // 跳转 navigateTo
        navigateTo({
            url: '../edit/edit?id=' + id,
        });
    },
    /**
     * 组件响应事件
     */
    _commonEvent: function () {
        switchTab({
            url:"../add/add",
        })
    },
    _moodEvent: function () {
        app.data.type = "mood"
        switchTab({
            url:"../add/add",
        })
    }
});

/**
 * 处理初始化页面列表数据
 */
function initData (page) {
    var diary = wx.getStorageSync('diary');
    if (diary.length) {
        diary.forEach(item => {
            var t = new Date(Number(item.time));
            item.time = dateFormate(t);
        });
        page.setData({
            lists: diary
        });
    } else {
        page.setData({
            lists: []
        });
    }
}